package com.anli02.service.impl;


import com.anli02.entity.dto.SessionwebUserDto;
import com.anli02.entity.pojo.User;

import com.anli02.entity.vo.R;
import com.anli02.exception.BusinessException;
import com.anli02.mapper.UserMapper;
import com.anli02.service.IUserService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.redisson.Redisson;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author author
 * @since 2024-10-08
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    @Autowired
    RedisTemplate redisTemplate;
    @Override
    public R login(String account, String password) {
        Object o = redisTemplate.opsForValue().get(account);
        if(o==null)
        {
            //弹出验证码-或者其他策略 查mysql
            //mysql也为空
            LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(User::getUsername, account); // 使用 Lambda 表达式引用字段 lambdaQueryWrapper.ge(User::getAge, 18);
            //加锁有必要吗，没有
            User user = this.baseMapper.selectOne(lambdaQueryWrapper);
            o=user;
            if(user==null)
            {
                redisTemplate.opsForValue().set(account,"");
                return R.error("账号或密码错误");
                //防止缓存穿透--
            }
            //插入user缓存到redis
            redisTemplate.opsForValue().set(account,user);
        }
        User user = (User) o;
        if(!user.getPassword().equals(password))
        {
            return R.error("账号或密码错误");
        }
        //登录成功给sessio
        SessionwebUserDto sessionwebUserDto = new SessionwebUserDto();
        sessionwebUserDto.setUserId(user.getUserid());
        sessionwebUserDto.setUsername(user.getUsername());
        return R.success(sessionwebUserDto);

    }

    @Override
    public R register(User user) {
        if(user==null||user.getPassword().isEmpty()||user.getPassword().isEmpty())
        {
            return  R.error("请补全参数");
        }
        //各类校验
        Object o = redisTemplate.opsForValue().get(user.getUsername());
        if(o!=null)
        {
            return R.error("账号已存在");
        }
        ///后续做xxl-job
/*        String keyRegister = "register"+user.getAccount();
        redisTemplate.opsForValue().set(keyRegister,user.getPassword());*/
        RedissonClient redissonClient = Redisson.create();
        //获取锁
        RLock loc=redissonClient.getLock("register");
        ///加锁
        try {
            boolean isLock=loc.tryLock(3, -1, TimeUnit.SECONDS);
            if(isLock)
            {
                int insert = this.baseMapper.insert(user);
                if(insert==0)
                {
                    return  R.error("注册失败");
                }
                //即时缓存
                redisTemplate.opsForValue().set(user.getUsername(),user);
            }



        }catch (Exception e)
        {
            throw  new BusinessException(500,"注册失败");
        }finally {
            if (loc != null && loc.isLocked()) {
                loc.unlock();
            }
        }

        return R.success("注册成功");
    }
}
